const Entry = require('../models/entry') //引入模型

exports.form = (req, res) => {
    res.render('post', {
        title: 'Post'
    });
};

exports.submit = (req, res, next) => {
    const data = req.body.entry; //来自表单中名为 "entry[]"的控件
    console.log(req.body)
    const user = res.locals.user; //加载用户数据的中间件
    const username = user ? user.name : null;
    const entry = new Entry({
        username: username,
        title: data.title,
        body: data.body
    });
    entry.save((err) => {
        if (err) return next(err);
        //根据 remoteUser 判断是否是api调用，改变返回
        if (req.remoteUser) {
            res.json({
                message: 'Entry added.'
            });
        } else {
            res.redirect('/');
        }
    });
};

exports.list = (req, res, next) => {
    Entry.getRange(0, -1, (err, entries) => { //获取消息 
        if (err) return next(err);
        res.render('entries', { //渲染响应
            title: 'Entries',
            entries: entries,
        });
    });
};